package LeetCode;

import java.util.HashSet;

public class LC_202_HappyNumber {

    public static void main(String[] args) {

    }

    static class Solution {

        public boolean isHappy(int n) {
            if (n == 0) return false;
            if (n == 1) return true;
            int temp = 0;
            boolean flag[] = new boolean[811];
            int yushu;
            while (true) {
                while (n != 0) {
                    yushu = n % 10;
                    n = n / 10;
                    temp += yushu * yushu;
                }
                if (temp == 1) return true;
                if (flag[temp])
                    return false;
                else
                    flag[temp] = true;
                n = temp;
                temp = 0;
            }
        }

    }

    static class Solution_2 {

        public boolean isHappy(int n) {
            if (n == 1 || n == -1) return true;
            HashSet<Integer> h = new HashSet<>();
            int m = 0;
            while (true) {
                while (n != 0) {
                    m = m + (n % 10) * (n % 10);
                    n = n / 10;
                }
                if (m == 1) return true;
                if (!h.add(m)) return false;
                n = m;
                m = 0;
            }
        }

    }

    static class Solution_3 {

        public boolean isHappy(int n) {
            int[] mark = new int[8];
            while (n > 1) {
                n = convert(n);
                if (n < 243) {
                    int sec = n >> 5;
                    int mask = 1 << (n & 0x1f);
                    if ((mark[sec] & mask) > 0) {
                        return false;
                    }
                    mark[sec] |= mask;
                }
            }
            return true;
        }

        private int convert(int n) {
            int sum = 0;
            while (n > 0) {
                int t = n % 10;
                sum += t * t;
                n /= 10;
            }
            return sum;
        }

    }

}